<?php

namespace app\admin\controller\app;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;

/**
 * App情报管理
 *
 * @icon fa fa-circle-o
 */
class Intel extends Backend
{

    /**
     * AppIntel模型对象
     * @var \app\common\model\AppIntel
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\app\Intel;
        $this->view->assign("mediatypeList", $this->model->getMediatypeList());
        $this->view->assign("recommendswitchList", $this->model->getRecommendswitchList());
        $this->view->assign("rtypeList", $this->model->getRtypeList());
        $this->view->assign("columnList", $this->model->getColumnList());
        $this->view->assign("verifyList", $this->model->getVerifyList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['user','usergroup.group'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user','usergroup.group'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $row) {
                $row->visible(['id','user_id','commentnum','pvnum','sharenum','praisenum','recommendswitch','rtype','rid','column','verify','updatetime','verifytime']);
                // $row->visible(['applabel']);
				// $row->getRelation('applabel')->visible(['name']);
				$row->visible(['user']);
				$row->getRelation('user')->visible(['group_id','nickname']);
                $row->visible(['usergroup']);
                // $row->getRelation('usergroup')->visible(['group']);
            }
            // return $list;

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 审核
     */
    public function verify()
    {
        $id = input('id');
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            // halt($params);
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['verifytime'] = time();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    // 删除新闻图片
                    $arr = model("AppIntelAttachment")->where('intel_id', $v['id'])->select();
                    if ($arr) {
                        foreach ($arr as $kk => $vv) {
                            model("AppIntelAttachment")->where('id', $vv['id'])->delete();
                            $attachmentFile = ROOT_PATH . '/public/uploads' . $vv['url'];
                            if (is_file($attachmentFile)) {
                                @unlink($attachmentFile);
                            }
                            //同步删除oss
                            $ftpcfg = get_addon_config('ftp');
                            if ($ftpcfg['ftp_usernmae'] && $ftpcfg['ftp_password']) {
                                $FTP = new \addons\ftp\library\Auth($ftpcfg['ftp_host'], $ftpcfg['ftp_port'], $ftpcfg['ftp_usernmae'], $ftpcfg['ftp_password'], $ftpcfg['ftp_ssh'], $ftpcfg['ftp_pasv']);
                                $FTP->del_file(str_replace('/', DIRECTORY_SEPARATOR, $vv['url']));
                                $FTP->close();
                            }
                        }
                    }
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
